package com.hmall.service.Impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.pojo.ItemDoc;
import com.hmall.pojo.RequestParams;
import com.hmall.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public PageDTO<ItemDoc> search(RequestParams params) throws IOException {
        //1.准备request
        SearchRequest request = new SearchRequest("item");
        //2.准备DSL
        //2.1query条件
        buildBasicQuer(request,params);
        //2.2分页
        int page = params.getPage();
        int size = params.getSize();
        request.source().from((page-1)*size).size(size);
        //2.3排序
        //2.4高亮
        //3.发请求
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //4.解析结果
        SearchHits searchHits = response.getHits();

        long total = searchHits.getTotalHits().value;

        SearchHit[] hits = searchHits.getHits();

        List<ItemDoc> list = new ArrayList<>(hits.length);
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            ItemDoc itemDoc = MAPPER.readValue(json, ItemDoc.class);

            list.add(itemDoc);
        }
        return new PageDTO<>(total,list);
    }



    @Override
    public void deleteItemById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("item", id.toString());
            // 2.发请求
            restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Autowired
    private ItemClient itemClient;

    @Override
    public void saveItemById(Long id) {
        try {
            // 1.查询商品数据
            Item item = itemClient.getById(id);
            // 2.准备Request
            IndexRequest request = new IndexRequest("item").id(id.toString());
            // 3.准备DSL
            request.source(MAPPER.writeValueAsString(new ItemDoc(item)), XContentType.JSON);
            // 4.发送请求
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void buildBasicQuer(SearchRequest request, RequestParams params) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)){
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        String  brand= params.getBrand();
        if (StringUtils.isNotBlank(brand)){
            boolQuery.must(QueryBuilders.matchQuery("brand",brand));
        }
        String  category= params.getCategory();
        if (StringUtils.isNotBlank(category)){
            boolQuery.must(QueryBuilders.matchQuery("category",category));
        }
        Long  maxPrice= params.getMaxPrice();
        Long  minPrice= params.getMinPrice();
        if (minPrice!=null&&maxPrice!=null){
            boolQuery.must(QueryBuilders.matchQuery("category",category));
        }
        request.source().query(boolQuery);
    }
}
